<?php
/**
 * Created by PhpStorm.
 * User: august
 * Date: 2021/2/18
 * Time: 16:54
 */

namespace Aug\Tools;


use ZipArchive;

class Zip
{

    const ERROR_DIR_NOT_EXIST = '错误：目录不存在';
    const ERROR_ZIP_NOT_LOADED = '错误：Zip扩展未安装';
    public static function addPathToZip($path, ZipArchive $zip)
    {
        if (!is_dir($path))
            throw new \Exception(self::ERROR_DIR_NOT_EXIST, 2);

        $handler = opendir($path);

        while (($filename = readdir($handler)) !== false) {
            if (!in_array($filename, ['.', '..'])) {
                $file = $path . '/' . $filename;
                if (is_dir($file)) {
                    self::addPathToZip($file, $zip);
                } else {
                    $zip->setCompressionIndex(3, ZipArchive::CM_DEFAULT);
                    // $zip->addFile($file, str_replace('/tmp/', '', $file));
                    $zip->addFile($file, str_replace(sys_get_temp_dir(). DIRECTORY_SEPARATOR, '', $file));
                }
            }
        }
    }

    private static function checkZipExtension()
    {
        if (!extension_loaded('zip')) {
            throw new \Exception(self::ERROR_ZIP_NOT_LOADED, 3);
        }
    }

    public static function dirToZip($paths, $zipName)
    {
        self::checkZipExtension();
        if (is_string($paths)) {
            $paths = [$paths];
        }

        $zip = new ZipArchive();

        if ($zip->open($zipName, ZipArchive::CREATE) === true) {
            foreach ($paths as $path) {
                self::addPathToZip($path, $zip);
            }
            $zip->close();
        }
        if (file_exists($zipName)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 压缩文件
     *
     * author: august 2021/4/2
     * @param string|array $file 要被压缩的文件
     * @param null $zipName 压缩包名称
     * @param int $compressLevel 压缩等级
     * @throws \Exception
     */
    public static function zipFile($file, $zipName = null, $compressLevel = 1)
    {
        if (!$file) {
            throw new \Exception("文件不能为空", 1);
        }

        $file = is_string($file) ? [$file] : $file;
        foreach ($file as $f) {
            Helper::checkFileExist($f);
        }
        self::checkZipExtension();

        $zip = new ZipArchive();
        $zipFile = empty($zipName) ? basename($file[0]) . '.zip' : $zipName;
        $baseZipFile = substr(basename($zipFile), 0, strrpos($zipFile, '.'));
        $zip->open($zipFile, ZipArchive::CREATE);
        foreach ($file as $i => $f) {
            $_baseFileName = basename($f);
            $zip->addFile($f, strncasecmp($_baseFileName, 'tmp', 3) ? $_baseFileName : $i . '_' . $baseZipFile);
        }

        $zip->close();
        return $zipFile;
    }
}